/**
 * Jul 13, 2012
 */
package ee.edi.common.service;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.jboss.resteasy.annotations.providers.jaxb.Formatted;
import org.jboss.resteasy.spi.Failure;

import ee.edi.common.ServiceException;
import ee.edi.common.resource.ErrorInfo;

/**
 * @author andrei
 *
 */
@Consumes({ MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_XML})
@Formatted
public abstract class RestService{

	protected @Context
	Request request;
	protected @Context
	HttpServletRequest servletRequest;
	public static Response buildErrorResponse(ServiceException e) {

		ErrorInfo info = e.getErrorInfo();
		info.trace = buildStackTrace(e.getCause());

		ResponseBuilder builder = Response.status(e.getStatus()).entity(info);

		return builder.build();
	}

	public static Response buildErrorResponse(Throwable cause) {
		if (cause.getCause() instanceof ServiceException)
			return buildErrorResponse((ServiceException) cause.getCause());
		if (cause instanceof Failure) {
			Response r = ((Failure) cause).getResponse();
			Response.Status status = Response.Status.INTERNAL_SERVER_ERROR;
			if (r != null)
				status = Response.Status.fromStatusCode(r.getStatus());
			return buildErrorResponse(new ServiceException(status, cause));
		}
		return buildErrorResponse(new ServiceException(
				Response.Status.INTERNAL_SERVER_ERROR, cause));
	}

	static String buildStackTrace(Throwable cause) {
		if (cause == null)
			return null;
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(os);
		cause.printStackTrace(ps);
		return os.toString();
	}

}
